/**
 * 智能体管理API接口
 */

import axios from 'axios'
import type {
  AIWebAgent,
  CreateAgentRequest,
  UpdateAgentRequest,
  AgentQueryParams,
  AgentListResponse,
  AgentStatusUpdateRequest,
  AgentVersionUpdateRequest,
  CloneAgentRequest,
  AgentConfigSummary
} from '@/types/agent'

// 基础配置 - 统一使用vite代理配置
const API_BASE_URL = '/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log('Agent API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Agent Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log('Agent API Response:', response.status, response.config.url)
    return response.data
  },
  (error) => {
    console.error('Agent Response Error:', error.response?.status, error.config?.url, error.response?.data)
    return Promise.reject(error)
  }
)

// 过滤空参数的工具函数
const filterEmptyParams = (params?: Record<string, any>) => {
  if (!params) return {}
  return Object.fromEntries(
    Object.entries(params).filter(([_, value]) => 
      value !== null && value !== undefined && value !== ''
    )
  )
}

// 智能体相关API
export const agentApi = {
  // 获取智能体列表
  getAgents: (params?: AgentQueryParams): Promise<AgentListResponse> => 
    apiClient.get('/agent/', { params: filterEmptyParams(params) }),
  
  // 创建智能体
  createAgent: (data: CreateAgentRequest): Promise<AIWebAgent> => 
    apiClient.post('/agent/', data),
  
  // 获取单个智能体详情
  getAgentById: (agentId: string): Promise<AIWebAgent> => 
    apiClient.get(`/agent/${agentId}`),
  
  // 更新智能体
  updateAgent: (agentId: string, data: UpdateAgentRequest): Promise<AIWebAgent> => 
    apiClient.put(`/agent/${agentId}`, data),
  
  // 删除智能体（软删除）
  deleteAgent: (agentId: string, deletedBy: string): Promise<{ message: string }> => 
    apiClient.delete(`/agent/${agentId}`, { params: { deleted_by: deletedBy } }),
  
  // 恢复已删除的智能体
  restoreAgent: (agentId: string, restoredBy: string): Promise<{ message: string }> => 
    apiClient.post(`/agent/${agentId}/restore`, null, { params: { restored_by: restoredBy } }),
  
  // 更新智能体状态
  updateAgentStatus: (agentId: string, data: AgentStatusUpdateRequest): Promise<AIWebAgent> => 
    apiClient.patch(`/agent/${agentId}/status`, data),
  
  // 更新智能体版本
  updateAgentVersion: (agentId: string, data: AgentVersionUpdateRequest): Promise<AIWebAgent> => 
    apiClient.patch(`/agent/${agentId}/version`, data),
  
  // 克隆智能体
  cloneAgent: (agentId: string, newAgentName: string, createdBy: string): Promise<AIWebAgent> => 
    apiClient.post(`/agent/${agentId}/clone`, null, { 
      params: { 
        new_agent_name: newAgentName, 
        created_by: createdBy 
      } 
    }),
  
  // 获取智能体配置摘要
  getAgentConfig: (agentId: string): Promise<AgentConfigSummary> => 
    apiClient.get(`/agent/${agentId}/config`),
  
  // 根据场景获取智能体列表
  getAgentsByScene: (sceneId: string, params?: { page?: number, page_size?: number, status?: string }): Promise<AgentListResponse> => 
    apiClient.get(`/agent/scene/${sceneId}`, { params: filterEmptyParams(params) }),

  // 启动助手 - 初始化Agent
  startAgent: (agent: AIWebAgent): Promise<any> => {
    // 确保agent_code字段存在，如果没有则默认为"chat"
    const agentCode = agent.agent_code || "chat";
    
    // 生成唯一的session_id
    const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const initRequest = {
      agent_id: agent.agent_id || `agent_${Date.now()}`,
      agent_code: agentCode,
      agent_name: agent.agent_name || "智能助手",
      scene_id: agent.scene_id || "",
      tenant_id: agent.tenant_id || "default",
      llm_code: agent.llm_code || "",
      embedding_code: agent.embedding_code || "",
      sys_prompt: agent.sys_prompt || "你是一个友好的AI助手，请用中文回答用户的问题。",
      status: String(agent.status || "1"),
      version: agent.version || "1.0.0",
      tools_list: agent.tools_list || [],
      mcp_list: agent.mcp_list || [],
      rag_list: agent.rag_list || [],
      memory_config: {
        type: "mem0", // 使用 （Mem0 + 数据库）
        scene_id: agent.scene_id || "",
        agent_id: agent.agent_id || `agent_${Date.now()}`,
        session_id: sessionId,
        user_id: "1", // 默认用户ID
        preload_history: true,
        auto_save: true,
        max_history_length: 50,
        langchain_params: {
          return_messages: true,
          memory_key: "chat_history",
          k: 10 // 窗口大小
        },
      },
      llm_params: {
        max_tokens: 4096
      }
    };
    
    console.log('启动助手请求数据:', initRequest);
    return apiClient.post(`/chat/init_agent`, initRequest);
  },

  // 发送消息给Agent（流式）
  sendMessageStream: async (message: string, sessionId?: string, onMessage?: (data: any) => void, sceneId?: string): Promise<void> => {
    try {
      const response = await fetch(`${API_BASE_URL}/chat/answer_stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ message, session_id: sessionId, scene_id: sceneId })
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('无法创建流读取器')
      }

      const decoder = new TextDecoder()
      
      try {
        while (true) {
          const { done, value } = await reader.read()
          
          if (done) {
            break
          }
          
          const chunk = decoder.decode(value)
          const lines = chunk.split('\n')
          
          for (const line of lines) {
            if (line.trim() && line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6))
                if (onMessage) {
                  onMessage(data)
                }
              } catch (error) {
                console.warn('解析SSE数据失败:', error, line)
              }
            }
          }
        }
      } finally {
        reader.releaseLock()
      }
    } catch (error) {
      console.error('流式请求失败:', error)
      throw error
    }
  },

  // 获取Agent状态
  getAgentStatus: (): Promise<any> => 
    apiClient.get(`/chat/agent_status`),

  // 重置Agent
  resetAgent: (): Promise<any> => 
    apiClient.post(`/chat/reset_agent`),

  // 处理人机交互响应 - 改为流式接口
  handleHumanInteractionResponse: (interaction_id: string, approved: boolean, message?: string): EventSource => {
    const params = new URLSearchParams({
      interaction_id,
      approved: approved.toString()
    });
    if (message) {
      params.append('message', message);
    }
    
    return new EventSource(`/api/chat/human_interaction_response?${params}`, {
      withCredentials: false
    });
  },
}

export default apiClient 